<?php

class MemberController extends Controller {

	/**
	 * @var string the default layout for the views. Defaults to
	 * '//layouts/column2', meaning using two-column layout. See
	 * 'protected/views/layouts/column2.php'.
	 */
	public $layout = '//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow',
				'actions'=>array(
					'index',
					'view',
					'create',
					'update',
					'admin',
					'delete',
				),
				'users'=>array('@'),
			),
			array('deny', // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id) {
		If (!Yii::app()->user->checkAccess('memberView')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$this->render('view', array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view'
	 * page.
	 * TODO: Make $birthDate and $expireDate into $memberDates array?
	 */
	public function actionCreate() {
		If (!Yii::app()->user->checkAccess('memberCreate')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$model = new Member;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['Member'])) {
			$model->attributes = $_POST['Member'];
			$model->ownerId = Yii::app()->user->id;
			$valid = $model->validate();
			foreach ($_POST['MemberDate'] as $key=>$value) {
				$date = new MemberDate;
				$date->attributes = $value;
				$valid = $date->validate() && $valid;
				$dates[] = $date;
			}
			foreach ($_POST['MemberAddress'] as $key=>$value) {
				$address = new MemberAddress;
				$address->attributes = $value;
				$valid = $address->validate() && $valid;
				$addresses[] = $address;
			}
			foreach ($_POST['MemberPhone'] as $key=>$value) {
				$phone = new MemberPhone('create');
				$phone->attributes = $value;
				if ($phone->value) {
					$valid = $phone->validate() && $valid;
				}
				$phones[] = $phone;
			}
			// File field could not be array?
			$image = new MemberImage;
			$image->attributes = $_POST['MemberImage'];
			$valid = $image->validate() && $valid;
			if ($valid && !$model->code) {
				// Try generate code automatically 10 times.
				for ($index = 0; $index < 10; $index++) {
					$model->code = RefMemberCode::generate();
					if ($model->validate()) break;
				}
			}
			if ($model->validate() && $valid) {
				$trans = Yii::app()->db->beginTransaction();
				try {
					if (!$model->save(false)) {
						$model->addError('name', 'Error while saving');
						throw new Exception('Member');
					}
					$model->addExpireDate();
					$model->addCardreq();
					foreach ($dates as $key=>$value) {
						if (!$model->addChild($value)) {
							$value->addError('value', 'Error while saving');
							throw new Exception("MemberDate #$key");
						}
					}
					foreach ($addresses as $key=>$value) {
						if (!$model->addChild($value)) {
							$value->addError('street', 'Error while saving');
							throw new Exception("MemberAddress #$key");
						}
					}
					foreach ($phones as $key=>$value) {
						if ($value->value) {
							if (!$model->addChild($value)) {
								$value->addError('value', 'Error while saving');
								throw new Exception("MemberPhone #$key");
							}
						}
					}
					if (!$model->addChild($image)) {
						$value->addError('file', 'Error while saving');
						throw new Exception("MemberImage #$key");
					}
					$trans->commit();
					$this->redirect(array('view', 'id'=>$model->_id));
				} catch (Exception $e) {
					$trans->rollback();
				}
			}
		} else {
			$model->gender = Member::GENDER_MAN;
			$dates = array(new MemberDate);
			$dates[0]->name = MemberDate::NAME_BIRTH_DATE;
			$addresses = array(new MemberAddress);
			$addresses[0]->name = MemberAddress::NAME_HOME;
			$image = new MemberImage;
			$image->name = MemberImage::NAME_PHOTO;
			$phones = array(new MemberPhone, new MemberPhone, new MemberPhone);
			$phones[0]->name = MemberPhone::NAME_HANDPHONE;
			$phones[1]->name = MemberPhone::NAME_HOME;
			$phones[2]->name = MemberPhone::NAME_OFFICE;
		}

		$data = array(
			'model'=>$model,
			'dates'=>$dates,
			'addresses'=>$addresses,
			'image'=>$image,
			'phones'=>$phones,
		);
		$this->render('create', $data);
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id) {
		If (!Yii::app()->user->checkAccess('memberUpdate')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$model = $this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['Member'])) {
			$model->attributes = $_POST['Member'];
			if ($model->save()) $this->redirect(array('view', 'id'=>$model->_id));
		}

		$this->render('update', array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		If (!Yii::app()->user->checkAccess('memberDelete')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if (!isset($_GET['ajax']))
					$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
				throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		If (!Yii::app()->user->checkAccess('memberList')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$dataProvider = new CActiveDataProvider('Member');
		$this->render('index', array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		If (!Yii::app()->user->checkAccess('memberManage')) {
			$s = 'You are not authorized to perform this action.';
			throw new CHttpException(403, $s);
		}

		$model = new Member('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['Member'])) $model->attributes = $_GET['Member'];

		$this->render('admin', array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id) {
		$model = Member::model()->findByPk((int) $id);
		if ($model === null)
				throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'member-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

}
